


import React, { Component } from 'react';
import PropTypes from 'prop-types';
import MyBtn from './MyBtn';


/*
 组件之间的通信 
 
 1. 父子 组件 
 <A>
    <B></B>
 </A>
 2. 兄弟组件 
 <A></A><B></B>

 props 传递数据
 state 修改数据 

 父组件如何修改子组件  (Props+Refs)

 父组件把组件的state 当着子组件的props 传递给子组件
 父组件修改 state 会二次render 子组件接收到变化的 props  从而实现子组件修改  

 ref   this.refs  对象获取 
 1. ref 作用于DOM 元素  指向这个真实的DOM元素
 2. ref 作用于组件  指向这个组件对象   


受控组件 Input 绑定了value ==> 必须使用onChange 

3. context

4. EventBus

5. 架构 (Mobx Redux)



*/
class MyProps1 extends Component {
    state = {
        count:1000,
        msg:"Are you happy?",
        word:"daydayup-2217"
    }
    changeCount=()=>{
        this.setState({
            count:this.state.count+1 
        })
    }

    changeMsg=(msg)=>{
        this.setState({
            msg 
        })
    }

    onChange=(e)=>{
        this.setState({
            word:e.target.value 
        })
        this.refs.one.style.color = "red";
        this.two.style.color = "blue"
        this.three.style.color = "orange"
    }

    changeChildNumber=()=>{
        // this.child 指向的子组件的 child 的this 
        this.child.setState({
            number:++this.child.state.number 
        })
    }

    change=()=>{
        // this.child 指向的是这个子组件 
        this.child.changeFlag()
    }
    render() {
        console.log(this)
        const {count , msg ,word } = this.state;
        return (
            <div>
                <h2 ref="one" >React 组件通信 -  (父改子)</h2>
                <h2 ref={el=>this.two=el }  >props 传递数据 </h2>
                <h2 ref={el=>this.three=el}>state 修改数据  </h2>
                <h2>count == {count } </h2>
                <h2>msg = {msg} </h2>
                <p>
                    <input type="text" value={word} onChange={this.onChange} />
                </p>
                <MyBtn text="count+1" onClick={this.changeCount}></MyBtn>
                <MyBtn text="changeMsg" onClick={()=>this.changeMsg("Hello React so easy ")}></MyBtn>
                <MyBtn text="child number add " onClick={this.changeChildNumber}></MyBtn>
                <MyBtn text="控制子组件的显示隐藏" onClick={this.change}></MyBtn>

                <hr/>
                <MyChild  ref={el=>this.child=el}  count={count} msg={msg} word={word} ></MyChild>
            </div>
        );
    }
}

class MyChild extends Component{
    state = {
        number:1 ,
        flag :true, 
    }

    changeFlag=()=>{
        this.setState({
            flag:!this.state.flag 
        })
    }

    render(){
        
        const {count,msg , word } = this.props 
        const {flag} = this.state;
        return (
            flag ? <div>
                <h2> MyChild - 1 - 子组件 </h2>
                <h2>count == {count} </h2>
                <h2>msg=  {msg}</h2>
                <h3>word = {word} </h3>
                <h2>number == {this.state.number} </h2>
            </div>:null 
        )
    }
}

export default MyProps1;
